package inet.app.controller.database;

import inet.app.model.object.KqGiaiRegion;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class DaoKQGiaiRegion extends DaoBase {

	private final static String selection = DBConfig.COL_KQGIAI_REGION_DATE
			+ "=?" + " and " + DBConfig.COL_KQGIAI_REGION_REGION + "=?";

	private String[] createSelectionArgs(String date, String region) {
		return new String[] { date, region };
	}

	public DaoKQGiaiRegion(Context context) {
		super(context);
	}

	private ContentValues createContentValueFromRow(KqGiaiRegion region) {

		ContentValues value = new ContentValues();
		value.put(DBConfig.COL_KQGIAI_REGION_DATE, region.getDate());
		value.put(DBConfig.COL_KQGIAI_REGION_REGION, region.getRegion());
		return value;
	}

	private KqGiaiRegion createRowFromCursor(Cursor cursor) {
		KqGiaiRegion region = new KqGiaiRegion();
		region.setId(cursor.getInt(cursor.getColumnIndex(DBConfig.COL_ID)));
		region.setDate(cursor.getString(cursor
				.getColumnIndex(DBConfig.COL_KQGIAI_REGION_DATE)));
		region.setRegion(cursor.getString(cursor
				.getColumnIndex(DBConfig.COL_KQGIAI_REGION_REGION)));
		return region;
	}

	public long insertRow(KqGiaiRegion region) {
		if (!dbConnection.openSession())
			return -1;
		ContentValues values = createContentValueFromRow(region);
		long insertId = dbConnection.insert(DBConfig.TABLE_KQGIAI_REGION, null,
				values);
		dbConnection.closeSession();
		return insertId;
	}

	public int deleteRow(String date, String region) {
		int res = -1;
		if (!dbConnection.openSession())
			return res;
		Cursor cursor = dbConnection.query(DBConfig.TABLE_KQGIAI_REGION, null,
				selection, createSelectionArgs(date, region), null, null, null);
		if (cursor != null) {
			int rows = cursor.getCount();
			if (rows > 0) {
				/** row is existed, then delete row */
				res = dbConnection.delete(DBConfig.TABLE_KQGIAI_REGION,
						selection, createSelectionArgs(date, region));
			} else {
				/** row is not existed */
				res = 0;
			}
		}
		cursor.close();
		dbConnection.closeSession();
		return res;
	}

	public KqGiaiRegion selectRow(String date, String region) {
		KqGiaiRegion row = null;
		try {
			Cursor cursor = null;
			if (!dbConnection.openSession())
				return row;
			cursor = dbConnection.query(DBConfig.TABLE_KQGIAI_REGION, null,
					selection, createSelectionArgs(date, region), null, null,
					null);
			if (cursor != null) {
				int rows = cursor.getCount();
				if (rows > 0) {
					/** row is existed, then get row info */
					cursor.moveToFirst();
					row = createRowFromCursor(cursor);
				}
			}
			cursor.close();
			dbConnection.closeSession();
		} catch (Exception ex) {
			dbConnection.closeSession();
		}
		return row;
	}

	public int deleteAll() {
		return deleteAll(DBConfig.TABLE_KQGIAI_REGION);
	}

}
